package dnl.toolbox.files;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Mimics the behavior of the 'tail' command.
 * 
 * @author Daniel Orr
 * 
 */
public class Tail {

	/**
	 * Gets the last lines of the given file.
	 * 
	 * @param f
	 *            the file to tail.
	 * @param numberOfLines
	 *            number of lines to tail.
	 * @return
	 * @throws IOException
	 */
	public static String tail(File f, int numberOfLines) throws IOException {
		ReverseFileReader reverseFileReader = new ReverseFileReader(f);
		StringBuilder sb = new StringBuilder();

		List<String> lines = new ArrayList<String>(numberOfLines);
		Collections.reverse(lines);
		for (int i = 0; i < numberOfLines; i++) {
			String s = reverseFileReader.readLine();
			lines.add(s);
			if (s == null)
				break;
		}

		for (String line : lines) {
			sb.append(line);
			sb.append("\n");
		}

		return sb.toString();
	}

}
